package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Title: TCPserver
 * @Author 郑雨杭
 * @Package TCP
 * @Date 2024/7/11 20:21
 * @description: TCP服务器
 */
public class TCPserver {
    //创建服务器socket
    private ServerSocket serverSocket = null;
    //初始化服务器socket，并且绑定端口

    public TCPserver(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    private void stact() throws IOException {
        //提示信息
        System.out.println("服务器启动");
        //创建线程池，实现并发访问
        ExecutorService service = Executors.newCachedThreadPool();
        //循环获取请求并返回响应
        while (true){
            //获得与客户端的连接
            Socket socket = serverSocket.accept();
            //为每个请求创建独立的线程实现并发
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(socket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket socket) throws IOException {
            //提供try获取输入输出流可以避免资源泄露的问题
            try (InputStream inputStream = socket.getInputStream();
                 OutputStream outputStream = socket.getOutputStream()) {
                //提示信息
                System.out.printf("[%s:%d] 客户端上线\n", socket.getInetAddress(), socket.getPort());
                //将输入流封装成Scanner
                Scanner input = new Scanner(inputStream);
                //循环获取请求
                while (true) {
                    //如果没有请求则返回客户端下线的提示信息
                    if (!input.hasNext()) {
                        System.out.printf("[%s:%d] 客户端下线\n", socket.getInetAddress(), socket.getPort());
                        break;
                    }
                    //得到请求
                    String req = input.next();
                    //根据请求计算响应
                    String resp = process(req);
                    //将输出流封装为PrintWriter
                    PrintWriter writer = new PrintWriter(outputStream);
                    //将响应返回
                    writer.println(resp);
                    //刷新缓冲区
                    writer.flush();
                    //打印提示信息
                    System.out.printf("[%s:%d] req=%s resp=%s\n", socket.getInetAddress(), socket.getPort(), req, resp);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                //关闭资源
                socket.close();
            }
    }


    //服务器根据请求获取响应
    private String process(String req) {
        return req;
    }

    //绑定端口并启动
    public static void main(String[] args) throws IOException {
        new TCPserver(9090).stact();
    }
}
